package org.shock.ss.sms.action.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.sun.faces.util.ToolsUtil;

import org.shock.ss.sms.commons.annotation.RightAnno;
import org.shock.ss.sms.commons.db.DbTools;
import org.shock.ss.sms.commons.utils.ReflexUtils;

import org.shock.ss.sms.bean.Tree;
import org.shock.ss.sms.bean.system.Dic;
import org.shock.ss.sms.bean.system.Module;
import org.shock.ss.sms.bean.system.UserInfor;

import org.shock.ss.sms.commons.dao.DaoFactory;
import org.shock.ss.sms.dao.system.impl.ModuleDaoImpl;

import org.shock.ss.sms.service.system.ModuleService;
import org.shock.ss.sms.service.system.impl.ModuleServiceImpl;
import org.shock.ss.sms.action.BaseAction;

public class ModuleAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	/** 获得service */
	private ModuleService ms = new ModuleServiceImpl((ModuleDaoImpl) DaoFactory.getDao("ModuleDao"));
	private Module module = new Module();
	private List list = new ArrayList();
	private Long node;
	private Long roleid;
	private String treeString;
	private String isMenu;// 是否菜单

	/** 模块管理首页* */
	@RightAnno(rightNote = "模块管理")
	public String moduleAdmin() throws Exception {
		return SUCCESS;
	}

	/** 生成模块树,用于extjs Tree* */
	public String genModuleTree() throws Exception {
		UserInfor userInfor = getUserInfor();
		if (userInfor.getIsadmin() != 1) {
			sqladd.append(" and id in(" + userInfor.getModids() + ")");
		}
		if (node != null) {
			sqladd.append(" and pid=" + node);
		}
		if ("yes".equals(isMenu)) {
			sqladd.append(" and showmenu=1");
		}
		log.debug(sqladd);
		String sql = "select * from " + Module.getTable() + " where 1=1" + sqladd + " order by paixu asc";
		List<Map> listMap = ms.listAll(sql);
		System.out.println(sql);
		for (Map map : listMap) {
			Tree tree = new Tree((String) map.get("id"), (String) map.get("name"), Integer.parseInt(map.get("leaf")
					+ "") == 0 ? false : true, (String) map.get("iconcls"), (String) map.get("url"), "mainFrame");
			list.add(tree);
		}
		jsonString = JSON.toJSONString(list);
		log.debug(jsonString);
		return SUCCESS;
	}

	/** 生成首页左边导航栏菜单* */
	public String genMenu() throws Exception {
		UserInfor userInfor = getUserInfor();
		if (userInfor.getIsadmin() != 1) {
			if (userInfor.getModids() == null) {
				userInfor.setModids("0");
			}
			sqladd.append(" and id in(" + userInfor.getModids() + ")");
		}
		sqladd.append(" and showmenu=1");
		String sql = "select * from " + Module.getTable() + " where pid=-1 " + sqladd + " order by paixu asc";
		System.out.println(sql);
		List<Map> listMap = ms.listAll(sql);
		StringBuffer sb = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		for (Map map : listMap) {
			sb.append("{title:\"" + map.get("name") + "\",iconCls:'"
							+ map.get("iconcls")
							+ "', border:false, html:\"<div id=\'tree" + map.get("id")
					+ "\' class=\'downMenu\'></div>\"},");
			sb2
					.append("var tree"
							+ map.get("id")
							+ " = new Ext.tree.TreePanel({id:'moduletree"
							+ map.get("id")
							+ "',iconCls:'"
							+ map.get("iconcls")
							+ "',width : 180,useArrows : true,autoScroll:true,animate : true,singleExpand : false,containerScroll : true,  border : false,loader : new Ext.tree.TreeLoader({url : _ctxPath + '/genModuleTree.do?isMenu=yes'}),rootVisible : false,root : {nodeType : 'async',id :"
							+ map.get("id")
							+ ",text : '模块管理',expanded : true}});tree"
							+ map.get("id")
							+ ".render('tree"
							+ map.get("id")
							+ "');tree"
							+ map.get("id")
							+ ".getRootNode().expand();tree"
							+ map.get("id")
							+ ".on(\"click\",function (node,e){if(node.isLeaf()){parent.mainFrame.src=node.attributes['href'];}});");
		}
		if (sb.lastIndexOf(",") > 0) {
			sb.deleteCharAt(sb.lastIndexOf(","));
		}
		jsonString = sb.toString();
		treeString = sb2.toString();
		log.debug(jsonString);
		return SUCCESS;
	}

	/** 生成帮助手册树，用于extjs */
	public String genHelpDocTree() throws Exception {
		UserInfor userInfor = getUserInfor();
		if (userInfor.getIsadmin() != 1 && !"guest".equals(userInfor.getYgzh())) {
			if (userInfor.getModids() == null) {
				userInfor.setModids("0");
			}
			sqladd.append(" and id in(" + userInfor.getModids() + ")");
		}
		sqladd.append(" and showmenu=1");
		List<Map> listMap = ms.listAll("select * from " + Module.getTable() + " where pid=" + node + " " + sqladd
				+ " order by paixu asc");
		for (Map map : listMap) {
			Tree tree = new Tree((String) map.get("id"), (String) map.get("name"), Integer.parseInt(map.get("leaf")
					+ "") == 0 ? false : true, (String) map.get("iconcls"), (String) map.get("url"), "mainFrame");
			list.add(tree);
		}
		jsonString = JSON.toJSONString(list);
		log.debug(jsonString);
		return SUCCESS;
	}

	/** 查看模块 * */
	@RightAnno(rightValue = "viewModule", rightNote = "模块查看")
	public String viewModule() throws Exception {
		String sql = "select m.*,ifnull(mm.name,'模块管理') as parentname from " + Module.getTable() + " m left join "
				+ Module.getTable() + " mm on m.pid=mm.id where m.id=" + module.getId();
		// System.out.println(sql);
		log.debug(sql);
		Map map = ms.view(sql);
		log.debug(map);
		jsonString = JSONObject.fromObject(map).toString();
		log.debug(jsonString);
		return SUCCESS;
	}

	/** 更新模块 * */
	@RightAnno(rightValue = "updateModule", rightNote = "更新模块")
	public String updateModule() throws Exception {
		ms.update(module);
		return SUCCESS;
	}

	/** 添加模块 * */
	@RightAnno(rightValue = "addModule", rightNote = "添加模块")
	public String addModule() throws Exception {
		log.info(ReflexUtils.rwritertoString(module));// 调试bean信息
		if (action.equals("before")) {// 显示添加页面
			list = ms.listAll("select id,name from " + Module.getTable() + " order by paixu");
			log.debug(list);
			return "before";
		}
		ms.add(module);
		return SUCCESS;
	}

	/** 删除模块 * */
	@RightAnno(rightValue = "delModule", rightNote = "删除模块")
	public String delModule() throws Exception {
		List<Long> idsList = new ArrayList<Long>();
		idsList.add(module.getId());
		String ids = DbTools.getSubIdsStr(idsList, Module.getTable(), "pid", module.getId() + "");
		String sql = "delete from " + Module.getTable() + " where id in (" + ids + ")";
		System.out.println(sql);
		log.debug(sql);
		ms.del(sql);
		return SUCCESS;
	}

	public String listAllModule() throws Exception {
		if (roleid != null) {
			sqladd.append("and id in (select modids from ckgl_role where id=" + roleid + ")");
			list = DbTools.getList("select name,id from " + Module.getTable() + " where 1=1 " + sqladd);
			jsonString = JSONArray.fromObject(list).toString();
			return SUCCESS;
		}
		String sql = "select name,id,iconcls,leaf from " + Module.getTable() + " where pid= " + node + sqladd
				+ " order by paixu";
		list = DbTools.getMapsInList(sql);
		List tmpList = new ArrayList();
		for (Map map : (ArrayList<Map>) list) {
			Tree tree = new Tree();
			tree.setId((String) map.get("id"));
			tree.setText((String) map.get("name"));
			tree.setIconCls((String) map.get("iconcls"));
			tree.setChecked(false);
			tree.setLeaf(false);
			tree.setFlg(Integer.parseInt(map.get("leaf") + "") == 0 ? false : true);
			tmpList.add(tree);
		}
		jsonString = JSONArray.fromObject(tmpList).toString();
		// System.out.println(jsonString);
		return SUCCESS;
	}

	public Module getModule() {
		return module;
	}

	public void setModule(Module module) {
		this.module = module;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public Long getNode() {
		return node;
	}

	public void setNode(Long node) {
		this.node = node;
	}

	public String getTreeString() {
		return treeString;
	}

	public Long getRoleid() {
		return roleid;
	}

	public void setRoleid(Long roleid) {
		this.roleid = roleid;
	}

	/**
	 * @return the isMenu
	 */
	public String getIsMenu() {
		return isMenu;
	}

	/**
	 * @param isMenu
	 *            the isMenu to set
	 */
	public void setIsMenu(String isMenu) {
		this.isMenu = isMenu;
	}
}
